<template>
  <view>
    <view @click="toDetail(item.goods_id)" v-for="(item, index) in goodsList" :key="index">
      <mygoods :item="item"></mygoods>
    </view>
  </view>
</template>

<script>
  import mygoods from '../../components/my_goods/my_goods.vue'
  export default {
    components: {
      mygoods
    },
    data() {
      return {
        // 参数对象my-goods
        queryObj: {
          // 搜索商品列表的关键字
          query: '',
          // 页码
          pagenum: 1,
          // 页容量
          pagesize: 10,
        },
        // 商品列表
        goodsList: [],
        // 商品总数
        total: 0,
        // 默认的空图片
        defaultPic: 'https://img3.doubanio.com/f/movie/8dd0c794499fe925ae2ae89ee30cd225750457b4/pics/movie/celebrity-default-medium.png',
        // 是否正在请求数据
        isloading: false
      };
    },
    onLoad(options) {
      this.query = options.query
      // 调用获取商品列表的方法
      this.getGoodsList()
    },
    methods: {
      // 跳转到商品详情
      toDetail(id) {
        uni.navigateTo({
          url: `/pages/goods_detail/main?goods_id=${id}`
        })
      },
      // 获取商品列表的方法
      async getGoodsList(isPull) {
        // 打开开关
        this.isLoading = true
        const {
          data: res
        } = await uni.$http.get('/api/public/v1/goods/search', this.queryObj)
        if (res.meta.status !== 200) return uni.$showMsg()
        // 保存数据
        this.total = res.message.total
        this.goodsList = [...this.goodsList, ...res.message.goods]
        if (isPull) {
          // 关闭加载框
          uni.stopPullDownRefresh()
        }
        // 关闭开关
        this.isLoading = false
      }

    },

    // 触底的事件
    onReachBottom() {
      // 判断是否还有下一页数据
      if (this.queryObj.pagenum * this.queryObj.pagesize >= this.total) return uni.$showMsg('数据加载完毕！')

      // 判断是否正在请求其它数据，如果是，则不发起额外的请求
      if (this.isloading) return

      this.queryObj.pagenum += 1
      this.getGoodsList()
    },
    // 下拉时会触发
    onPullDownRefresh() {
      // 重置数据源
      this.queryObj.pagenum = 1
      this.goodsList = []
      this.total = 0
      this.isLoading = false
      // 重新发送请求
      this.getGoodsList(true)
    },
  }
</script>

<style lang="scss">
  .goodsList {
    padding: 5px;

    .goodsitem {
      display: flex;
      padding: 10px 0;
      border-bottom: 1px solid #ccc;

      .img {

        image {
          width: 130px;
          height: 90px;
        }
      }

      .info {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        padding: 6px 0px;
        margin-left: 10px;

        .title {
          font-size: 14px;
          word-break: break-all;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          /* 这里是超出几行省略 */
          overflow: hidden;
        }

        .price {
          color: #c00000
        }
      }
    }
  }
</style>
